package com.pow.service.impl;


import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.pow.entity.Permission;
import com.pow.repository.PermissionRepository;
import com.pow.service.PermissionService;
import com.pow.util.FenyeUtil;

@Service
public class PermissionServiceImpl implements PermissionService {

	@Autowired
	private PermissionRepository PermissionRepository;
	@Override
	public FenyeUtil<Permission> findByPage(Permission p, Integer page, Integer limit) {
		// TODO Auto-generated method stub
		Pageable pageable = PageRequest.of(page-1, limit);
		Page<Permission> pages = PermissionRepository.findAll(get(p),pageable);
		FenyeUtil<Permission> fenye=new FenyeUtil<>();
		fenye.setData(pages.getContent());
		fenye.setCount((int)pages.getTotalElements());
		return fenye;
	}

	private Specification<Permission> get(Permission p) {
		// TODO Auto-generated method stub
		return new Specification<Permission>() {
			
			@Override
			public Predicate toPredicate(Root<Permission> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				return predicate;
			}
		};
	}

	@Override
	public String DeleteById(String permissionId) {
		// TODO Auto-generated method stub
		try {
			PermissionRepository.deleteById(permissionId);
		    return "操作成功";
		} catch (Exception e) {
			System.out.println(e.getMessage());
			// TODO: handle exception
			return "操作失败";
		}
	}

	@Override
	public String AddAndUpd(Permission p) {
		// TODO Auto-generated method stub
		try {
			PermissionRepository.saveAndFlush(p);
		    return "操作成功";
		} catch (Exception e) {
			// TODO: handle exception
			return "操作失败";
		}
	}

}
